package cn.itcast.travel.service.impl;

import cn.itcast.travel.domain.blog;
import cn.itcast.travel.domain.blogger;
import cn.itcast.travel.service.BloggerService;
import cn.itcast.travel.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class BloggerServiceImpl implements BloggerService {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    //用户登录
    @Override
    public blogger login(blogger b) {
        blogger b1=null;
        try{
            String sql="select * from t_blogger where userName=? and password=?";
            b1=template.queryForObject(sql,new BeanPropertyRowMapper<blogger>(blogger.class),b.getUserName(),b.getPassword());
        }catch (Exception e){

        }
        return b1;
    }

    //检查用户是否存在
    public blogger iscunzai(String b){
        blogger bgis=null;
        try {
            String sql="select * from t_blogger where userName=?";
            bgis=template.queryForObject(sql,new BeanPropertyRowMapper<blogger>(blogger.class),b);
        }catch (Exception e){

        }
        return bgis;
    }
    //用户注册
    @Override
    public boolean register(blogger b) {
        blogger bgg=iscunzai(b.getUserName());
        if(bgg!=null){
            return false;
        }else{
            String sql1="insert into t_blogger (userName, password, profile, nickName, birthday, aventer) value(?,?,?,?,?,?);";
            template.update(sql1,b.getUserName(),b.getPassword(),b.getProfile(),b.getNickName(),b.getBirthday(),b.getAventer());
            return true;
        }
    }

    //获取发表过的博客
    @Override
    public List<blog> Personalblog(String id) {
        List<blog> bs=null;
        String sql="select *,id bgid from t_blog where bloggerid=?";
        bs=template.query(sql,new BeanPropertyRowMapper<blog>(blog.class),id);
        return bs;
    }

    //获取收藏的博客
    @Override
    public List<blog> allcollection(String id) {
        List<blog> bs=null;
        String sql="select *,t_collection.bgid bgid from t_collection join t_blog tb on tb.id = t_collection.bgid where t_collection.bloggerid=?";
        bs=template.query(sql,new BeanPropertyRowMapper<blog>(blog.class),id);
        return bs;
    }

    //删除发表过的文章或者收藏的文章
    @Override
    public void deleteblog(String which, String bgid,String bloggerid) {
        if(which.equals("2")){
            String sql1="delete from t_collection where bgid=?;";
            String sql2="delete from t_comment where blogid=?;";
            String sql="delete from t_blog where id=?";
            template.update(sql1,bgid);
            template.update(sql2,bgid);
            template.update(sql,bgid);
        }else{
            String sql="delete from t_collection where bgid=? and bloggerid=?";
            template.update(sql,bgid,bloggerid);
        }
    }
}
